/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.network;
import java.io.*;
import java.net.*;
import com.cse.p2p.common.*;
import com.cse.p2p.database.ClientDatabase;
import com.cse.p2p.database.ServerDatabase;
import com.cse.p2p.hash.HashImplement;
import com.cse.p2p.localfile.LocalFile;
import java.lang.ExceptionInInitializerError;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

/**
 *
 * @author TuyetNgan
 */
public class ClientReceiveDataTask extends Thread {
     private InputStream is = null;
        private Socket socket = null;
//        private int pieceID;
//        private int fileID;
//        private String pieceHash;
//        private String filePath;
        private byte[] content;
        private String IPsender;

        public ClientReceiveDataTask(Socket s){
            this.socket = s;
//            this.pieceID = id;
//            this.fileID = fid;
//            this.pieceHash = hash;
//            this.filePath = path;
        }
        public void  newConnection(){

            try{
                is = socket.getInputStream();
            }
            catch(IOException e){}
        }
        public void closeConnection(){
			try {
                socket.close();
			}
			catch (IOException e){}
        }
        public byte[] getContent(){
            return content;
        }

        public String getIP(){
            return IPsender;
        }
        @Override
        public void run() {
            newConnection();
            System.out.println("Client receiving ... ");
            /* receive file from server */
            try {
                byte[] mybytearray = new byte[client.logic.ClientLogicImplement.choosePiecesSize()];
                int count = 0;
                while( is.read(mybytearray, 0, mybytearray.length) != -1){
                    System.out.println(count++);
                    content = mybytearray;
                    IPsender = this.socket.getRemoteSocketAddress().toString();
//                    try {
//                        if(LocalFile.writeFiletoDisk(filePath, mybytearray))
//                            ClientDatabase.NewPiece(pieceID, fileID, pieceHash);
//                        else
//                            throw new UnsupportedOperationException("waiting GUI");
//                    } catch (SQLException ex) {
//                        Logger.getLogger(ReceiveTask.class.getName()).log(Level.SEVERE, null, ex);
//                    }

                }

                System.out.println("Client recieved file or piece");
            } catch (EOFException ex) {}
            catch (UnknownHostException i){}
            catch (IOException i){}
            closeConnection();
        }
}
